package com.etc.dao.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.sql.rowset.CachedRowSet;

import com.etc.dao.IUserDao;
import com.etc.entity.Users;
import com.etc.util.DBUtil;

public class UsersDaoImpl implements IUserDao {

	/**
	 * 根据用户名和密码查询用户
	 */
	@Override
	public Users queryUsersByNameandPwd(String userName, String userPwd) {
		CachedRowSet crs = DBUtil.execQuery("select * from admins where adminName=? and adminPwd=?", userName,userPwd);
		Users user=null;
		try {
			while(crs.next()) {
				int uid = crs.getInt(1);
				String uname = crs.getString(2);
				String upwd = crs.getString(3);
				int state = crs.getInt(4);
				int leval = crs.getInt(5);
				String userImg = crs.getString(6);
				user = new Users(uid, uname, upwd, state, leval,userImg);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return user;
	}

	@Override
	public List<Users> queryUsers() {
		CachedRowSet crs = DBUtil.execQuery("select * from users");
		Users user=null;
		List<Users> list=new ArrayList<>();
		try {
			while(crs.next()) {
				int uid = crs.getInt(1);
				String uname = crs.getString(2);
				String upwd = crs.getString(3);
				int state = crs.getInt(4);
				int leval = crs.getInt(5);
				user = new Users(uid, uname, upwd, state, leval);
				list.add(user);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public boolean addUsers(Users user) {
		return DBUtil.executeUpdate("insert into users values(null,?,?,?,?,?)", user.getUserName(),user.getUserpwd(),user.getUserStatus(),user.getUserLevel(),user.getUserImg());
	}

	@Override
	public boolean register(String userName, String userPwd,String userImg) {
		// 注册的是普通用户，所以等级默认为1，状态默认为1
		return DBUtil.executeUpdate("insert into users values(null,?,?,1,1,?)", userName,userPwd,userImg);
	}

	@Override
	public boolean queryByName(String uname) {
		CachedRowSet crs = DBUtil.execQuery("select * from users where userName=?",uname);
		Users user=null;
		try {
			while(crs.next()) {
				int uid = crs.getInt(1);
				String userName = crs.getString(2);
				String upwd = crs.getString(3);
				int state = crs.getInt(4);
				int leval = crs.getInt(5);
				user = new Users(uid, userName, upwd, state, leval);
			}
			if(user!=null) {
				return true;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

}
